<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model
        ref="form"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :model="model"
        :rules="validatorRules"
        slot="detail"
      >
        <a-row class="form-row" :gutter="16">
          <a-col :lg="8">
            <a-form-model-item label="报告名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reportName">
              <a-input v-model="model.reportName" placeholder="请输入报告名称"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24" >
            <a-form-model-item label="创建日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createDate">
              <j-date placeholder="请选择创建日期" v-model="model.createDate" style="width: 100%" />
            </a-form-model-item>
          </a-col> -->
          <a-col :lg="16">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24" >
            <a-form-model-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="userId">
              <a-input v-model="model.userId" placeholder="请输入创建人" ></a-input>
            </a-form-model-item>
          </a-col> -->
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="字段定义" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="userReportsFieldTable.loading"
          :columns="userReportsFieldTable.columns"
          :dataSource="userReportsFieldTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
        />
      </a-tab-pane>
      <a-tab-pane tab="计算范围" :key="refKeys[1]" :forceRender="true">
        <!-- <j-select-data-slot
              placeholder="请选择槽号"
              :multi="true"
              :buttons="false"
              v-model="userReportsRowTable.dataSource"
            ></j-select-data-slot>

        <div v-for="obj in userReportsRowTable.dataSource" :key="obj">
          {{ obj.slotName }}
        </div> -->
        <select-data-slot ref="selectDataSlot" @change="selectDataSlotChange"></select-data-slot>

        <j-vxe-table   v-show="false"
          keep-source
          :ref="refKeys[1]"
          :loading="userReportsRowTable.loading"
          :columns="userReportsRowTable.columns"
          :dataSource="userReportsRowTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JSelectDataSlot from '@/components/jeecgbiz/JSelectDataSlot2'
import SelectDataSlot from '@/views/corp/userReports/SelectDataSlot'

export default {
  name: 'UserReportsForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    JSelectDataSlot,
    SelectDataSlot,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0 ,
      validatorRules: {
        reportName: [{ required: true, message: '请输入报告名称!' }],
        createDate: [{ required: true, message: '请输入创建日期!' }],
      },
      refKeys: ['userReportsField', 'userReportsRow'],
      tableKeys: ['userReportsField', 'userReportsRow'],
      activeKey: 'userReportsField',
      // 字段定义
      userReportsFieldTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '字段名称',
            key: 'fieldName',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '类型',
            key: 'fieldType',
            width: '18%',
            type: JVXETypes.select,
            options: [
              // 下拉选项
              { title: '运算结果', value: '运算结果' },
              { title: '参考值', value: '参考值' },
              { title: '处理措施', value: '处理措施' },
            ],
            defaultValue: '运算结果',
            placeholder: '请选择${title}',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '算法名称',
            key: 'fieldRefName',
            type: JVXETypes.popup,
            width: '180px',
            popupCode: 'user_formula_select',
            field: 'id,formula_name',
            orgFields: 'id,formula_name',
            destFields: 'fieldRefId,fieldRefName', 
          },
          {
            title: '算法ID',
            key: 'fieldRefId',
            type: JVXETypes.input,
            width: '280px',
            disabled: true,
            placeholder: '请选择${title}',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '序号',
            key: 'orderNo',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: '0',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
        ],
      },
      // 计算范围
      userReportsRowTable: {
        loading: false,
        dataSource: [],
        columns: [
          // {
          //   title: '报表ID',
          //   key: 'reportId',
          //    type: JVXETypes.input,
          //   width:"200px",
          //   placeholder: '请输入${title}',
          //   defaultValue:'',
          //   validateRules: [{ required: true, message: '${title}不能为空' }],
          // },

          // {
          //   title: '槽号',
          //   key: 'slotName',
          //   type: JVXETypes.popup,
          //   popupCode: 'data_slot_select',
          //   field: 'slot_id',
          //   orgFields: 'slot_id',
          //   destFields: 'slotName',
          //   defaultValue: '',
          //   placeholder: '请选择${title}',
          //   validateRules: [{ required: true, message: '${title}不能为空' }],
          // },
          {
            title: '槽号',
            key: 'slotName',
            type: JVXETypes.selectDictSearch,
            // 【字典表配置信息】：数据库表名,显示字段名,存储字段名
            dict: 'data_slot,slot_id,slot_id',
          },
        ],
      },
      url: {
        add: '/userReports/userReports/add',
        edit: '/userReports/userReports/edit',
        queryById: '/userReports/userReports/queryById',
        userReportsField: {
          list: '/userReports/userReports/queryUserReportsFieldByMainId',
        },
        userReportsRow: {
          list: '/userReports/userReports/queryUserReportsRowByMainId',
        },
      },
      checkedList: [],
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    addBefore() {
      this.userReportsFieldTable.dataSource = []
      this.userReportsRowTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.userReportsField.list, params, this.userReportsFieldTable)
        this.rowData(this.url.userReportsRow.list, params, this.userReportsRowTable)
      }
    },
    rowData(url, params, tab, success) {
      var that = this
      tab.loading = true
      getAction(url, params)
        .then((res) => {
          let { result } = res
          let dataSource = []
          if (result) {
            if (Array.isArray(result)) {
              dataSource = result
            } else if (Array.isArray(result.records)) {
              dataSource = result.records
            }
          }
          tab.dataSource = dataSource
          dataSource.forEach((element) => {
            that.checkedList.push(element.slotName.trim())
          })
          that.$refs.selectDataSlot.setCheckedList(that.checkedList)
          typeof success === 'function' ? success(res) : ''
        })
        .finally(() => {
          tab.loading = false
        })
    },
    selectDataSlotChange(ckValus) {
      var dt = []
      for (let i = 0; i < ckValus.length; i++) { 
        dt.push({ id: i + 1, slotName: ckValus[i] })
      }
      this.userReportsRowTable.dataSource = dt
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        userReportsFieldList: allValues.tablesValue[0].tableData,
        userReportsRowList: allValues.tablesValue[1].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
  },
}
</script>

<style scoped>
</style>